package io.renren.service.impl;

import io.renren.dao.EmpBaseinfoDao;
import io.renren.dao.SocialSecurityAreaBasicDao;
import io.renren.dao.SysOfficeDao;
import io.renren.entity.*;
import io.renren.service.BaseService;
import io.renren.service.CustomBaseinfoService;
import io.renren.utils.FastJsonUtils;
import io.renren.utils.Global;
import io.renren.utils.HttpClientUtils;
import io.renren.utils.Sha1Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import io.renren.dao.CustomSettlementDao;
import io.renren.service.CustomSettlementService;
import org.springframework.transaction.annotation.Transactional;


@Service("customSettlementService")
public class CustomSettlementServiceImpl extends BaseService implements CustomSettlementService {
	@Autowired
	private CustomSettlementDao customSettlementDao;
	@Autowired
	private SocialSecurityAreaBasicDao socialSecurityAreaBasicDao;
	@Autowired
	private CustomBaseinfoService customBaseinfoService;
	
	@Override
	public CustomSettlementEntity queryObject(String id){
		return customSettlementDao.queryObject(id);
	}
	
	@Override
	public List<CustomSettlementEntity> queryList(Map<String, Object> map){
		return customSettlementDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return customSettlementDao.queryTotal(map);
	}

	//新增页面下拉菜单名目
	private static String[] selectInfos = new String[]{"areaBaseId","area"};


	@Override
	public void save(CustomSettlementEntity customSettlement){
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		customSettlement.setId(id);
		customSettlementDao.save(customSettlement);
	}
	
	@Override
	public void update(CustomSettlementEntity customSettlement){
		customSettlementDao.update(customSettlement);
	}
	
	@Override
	public void delete(String id){
		customSettlementDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		customSettlementDao.deleteBatch(ids);
	}

	@Override
	@Transactional
	public void startSynToB1() throws Exception {
		logger.info("与b1进行数据同步开始");
		Map<String, Object> params = new HashMap<String, Object>();
		String key = Global.getConfig("b1key");// 获取key
		String url = Global.getConfig("b1url1");// 获取url
		logger.info("key:" + key);
		logger.info("url:" + url);
		params.put("sfjsd", "1");
		String sign = Sha1Util.SHA1(params, key);// 计算签名
		logger.info("sign:" + sign);
		params.put("sign", sign);

		String result = HttpClientUtils.doPost(url, params);// 发送请求

		if (result != null) {
			result = result.replace("null", "''");
			Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
			if (b1Map != null && b1Map.size() > 0) {
				if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
					logger.info("data"+b1Map.get("data"));
					List<HashMap> dataList = FastJsonUtils.toList(String.valueOf(b1Map.get("data")), HashMap.class);
					//System.out.println("dataList.size:"+dataList.size());
					List<CustomSettlementEntity> addCustList = new ArrayList();
					if(dataList!=null&&dataList.size()>0){
						List<HashMap> addList = new ArrayList<HashMap>();
						List<HashMap> updateList = new ArrayList<HashMap>();
						List<HashMap> deleteList = new ArrayList<HashMap>();
						List<CustomSettlementEntity> custList= new ArrayList<CustomSettlementEntity>();
//						List<DepartmentTree> departmentList= new ArrayList<DepartmentTree>();
						StringBuffer idSb = new StringBuffer();
						String operteType = null;
						String b1Id = null;
						for(HashMap tMap:dataList){
							operteType = tMap.get("operteType").toString();// operteType 0：增加  1：更新  2：删除
							b1Id = tMap.get("cardCode").toString();
							if("0".equals(operteType)){
								addList.add(tMap);
							}else if("1".equals(operteType)){
								updateList.add(tMap);
							}else if("2".equals(operteType)){
								deleteList.add(tMap);
							}
							idSb.append(b1Id+",");
						}

						if(addList.size()>0){
							for(HashMap aMap:addList){
								CustomSettlementEntity  custTmp = new CustomSettlementEntity();
								String id = UUID.randomUUID().toString().replaceAll("-", "");
								custTmp.setId(id);
								custTmp.setUnitName(String.valueOf(aMap.get("cardName")));
								custTmp.setContractNo(String.valueOf(aMap.get("u_fjbh")));
								custTmp.setSettlementNo(String.valueOf(aMap.get("cardCode")));
								custTmp.setSettlementCode(String.valueOf(aMap.get("cardFname")));
								custTmp.setSettlementName(String.valueOf(aMap.get("cardName")));

								custList.add(custTmp);
							}
							logger.info("批量保存数据开始");
							customSettlementDao.saveBatch(custList);
							addCustList.addAll(custList);
							logger.info("批量保存数据完成");
						}

						if(updateList.size()>0){
							custList= new ArrayList<CustomSettlementEntity>();
							for(HashMap aMap:updateList){
								CustomSettlementEntity  custTmp = new CustomSettlementEntity();
								custTmp.setUnitName(String.valueOf(aMap.get("cardName")));
								custTmp.setContractNo(String.valueOf(aMap.get("u_fjbh")));
								custTmp.setSettlementNo(String.valueOf(aMap.get("cardCode")));
								custTmp.setSettlementCode(String.valueOf(aMap.get("cardFname")));
								custTmp.setSettlementName(String.valueOf(aMap.get("cardName")));
								custList.add(custTmp);
							}
							logger.info("批量更新数据开始");
							customSettlementDao.updateBatch(custList);
							logger.info("批量更新数据完成");
						}

						if(deleteList.size()>0){
							custList= new ArrayList<CustomSettlementEntity>();
							for(HashMap dMap:deleteList){
								CustomSettlementEntity  custTmp = new CustomSettlementEntity();
								custTmp.setSettlementNo(String.valueOf(dMap.get("cardCode")));
								custList.add(custTmp);
							}
							logger.info("批量删除数据开始");
							customSettlementDao.deleteBatchByList(custList);
							logger.info("批量删除数据完成");
						}
						/*if(1==1){
							throw new Exception();
						}*/
						//	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

//						logger.info("开始更新b1库本次同步的所有记录的状态");
//						String urlBack =  Global.getConfig("b1url7");// 获取url，已同步
//						Map<String,Object> paramsBack = new HashMap<String,Object>();
//						String b1Ids = idSb.toString();
//						b1Ids = b1Ids.substring(0,b1Ids.lastIndexOf(","));
//						paramsBack.put("conId",b1Ids );
//						logger.info("b1Ids:"+b1Ids);
//						String signBack = Sha1Util.SHA1(paramsBack, key);// 计算签名
//						logger.info("signBack:" + signBack);
//						paramsBack.put("sign", signBack);
//						logger.info("urlBack:"+urlBack);
//						String backResult = HttpClientUtils.doPost(urlBack, paramsBack);// 发送请求
//						if (backResult != null) {
//							Map<String, Object> b1BackMap = new HashMap<String, Object>();
//							b1BackMap = FastJsonUtils.stringToCollect(backResult);
//							if (!(b1BackMap.get("isSuc").equals("y"))) {
//								if(addCustList.size()>0){
//									logger.error("更新b1同步状态失败，删除本地本次新增记录");
//									customSettlementDao.deleteBatchByList(addCustList);
//								}
//								throw new Exception();
//							}
//						}else{
//							throw new Exception();
//						}
						customBaseinfoService.startSynToB1();
						logger.info("客户和结算点都同步完成");

					}else{
						logger.info("没有要更新数据，同步完成");
					}
				} else {
					throw new Exception();
				}
			}
		} else {
			throw new Exception();
		}




	}


	@Override
	public Map<String, Object> getListinfo() {
		Map<String, Object> map = new HashMap<>();
		for (String selectInfo : selectInfos) {
			map.put(selectInfo,customSettlementDao.getSelectInfo());
		}
		List<SysOfficeEntity> deptlist = customSettlementDao.getDeptList();
		List<SysUserEntity> userlist = customSettlementDao.getUserList();
		map.put("settle_mode",customSettlementDao.getDicInfo("settle_mode"));
		map.put("deptlist",deptlist);
		map.put("userlist",userlist);
		return map;
	}


	public String  queryByIndex(String index) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("index",index);
		List<SocialSecurityAreaBasicEntity> list = socialSecurityAreaBasicDao.queryByIndex(map);
		String value="";
		if(list!=null&&list.size()>0){
			SocialSecurityAreaBasicEntity socialSecurityAreaBasic=list.get(0);
			value=socialSecurityAreaBasic.getProvince()+socialSecurityAreaBasic.getCity()+socialSecurityAreaBasic.getDistrict();
		}
		return value;
	}

	@Override
	public List<CustomSettlementEntity> getTree() {
		return customSettlementDao.getSettlementList();
	}

	/*@Override
	public Map<String, Object> getSelectList(){
		List<SysOfficeEntity> deptlist = customSettlementDao.getDeptList();
		List<SysUserEntity> userlist = customSettlementDao.getUserList();
		List<HashMap<String, Object>> arealist = empBaseinfoDao.getSelectInfo("area");
		Map<String, Object> map = new HashMap<>();
		map.put("deptlist",deptlist);
		map.put("userlist",userlist);
		map.put("arealist",arealist);
		return map;
	}*/

}
